from datetime import datetime, date,timedelta
import re
import time
import pandas as pd
import tushare as ts
import numpy as np

import requests

import simplejson
import random

import json
def gn_bk(code_="GN300036", daytime="20210930",page="1",*args,**kwargs):
    url = 'http://api.quchaogu.com/event/hangye/stockfordxw?start_time=930&pagecount=20&last_time=1500&end_time=1500&filter_date={}&page=1&code={}&apiversion=8.7&backgroundcolor=white&vaid=&oaid=&device_id=a865166028641465'.format(
        daytime, code_)
    # print(url)
    headers = {
        'User-Agent': 'DxwApp:4.2.0.156 | android:5.1.1 | samsung:SM-G9730 | sc:360,640 | did:a865166028641465 | oaid: | vaid: | did:a865166028641465 | idfa: | qd:wap | av:8.7 | uid:7%253A8%253A2206148315%253Aa865166028641465%253A6%253A1605528165%253A289aadf8d7a35a1',
        'Host': 'api.quchaogu.com',
        'Connection': 'Keep-Alive',
        'Accept-Encoding': 'gzip',
        'Cookie': 'web_uinfo=%7B%22uactime%22%3A1605530211%7D; app_ua=DxwApp%3A4.2.0.156+%7C+android%3A5.1.1+%7C+samsung%3ASM-G9730+%7C+sc%3A360%2C640+%7C+did%3Aa865166028641465+%7C+oaid%3A+%7C+vaid%3A+%7C+did%3Aa865166028641465+%7C+idfa%3A+%7C+qd%3Awap+%7C+av%3A8.7+%7C+uid%3A7%25253A8%25253A2206148315%25253Aa865166028641465%25253A6%25253A1605528165%25253A289aadf8d7a35a1; vistor_uuid=32717565199866433743603; web_qtstr=7%3A8%3A2206148315%3Aa865166028641465%3A6%3A1605528165%3A289aadf8d7a35a1'
    }
    params = {
        'start_time': '930',
        'last_time': '1500',
        'end_time': '1500',
        'filter_date': '{}'.format(daytime),
        'pagecount': '20',
        'page': '{}'.format(page),
        'code': '{}'.format(code_),
        'apiversion': '8.7',
        'backgroundcolor': 'white',
        'vaid': '',
        'oaid': '',
        'device_id': 'a865166028641465'}

    r = requests.get(url, headers=headers, params=params)
    if r.status_code == 200:
        r = r.text.encode('utf-8').decode('unicode_escape')
        #print("->回测时间:",simplejson.loads(r, strict=False)['data']['day'])  # 20210330
        a = simplejson.loads(r, strict=False)['data']['stock_list']
        df = pd.DataFrame(a)
        #print(df)
        """text         16 non-null object
    color        16 non-null int64
    icons        16 non-null object   *****
    type         16 non-null object
    fixed_ext    16 non-null object
    remark       16 non-null object
    param        16 non-null object   *****
    bold         16 non-null int64
    next_tags    16 non-null object   *****
    is_new       16 non-null int64    *****
    is_yd        1 non-null float64   *****"""
        # is_new  is_yd (异动)
        if df.empty==True:#补丁，对空dataframe进行ruturn none
            # print("::::::::",df)
            return df
        try:
            result_ = df[0].apply(pd.Series)[["icons", "param", "next_tags", "is_new", "is_yd"]]
            #错误处,补丁1修改了行业龙为nan的情况.
            result_["param"]=pd.DataFrame({"param": pd.DataFrame(result_.param.values.tolist())['code']})
        except:
            result_ = df[0].apply(pd.Series)[
                ["icons", "param", "next_tags", "is_new"]]  # [["icons","param","next_tags","is_new","is_yd"]]
            # print(pd.DataFrame(result_))
            result_ = pd.DataFrame({"param": pd.DataFrame(result_.param.values.tolist())['code'],
                                    'icons': np.concatenate(result_.icons.values), "next_tags": result_.next_tags,
                                    "is_new": result_.is_new})  # dataframe里面列的数据类型是list的列拆分成多个行
            #print(result_)
            # print(result_.icons.str.split("/").apply(pd.Series)[5].str.split(".").apply(pd.Series)[0])

        a_list = []
        for i in result_.next_tags:
            # print(i)#['http://idxw.oss-cn-beijing.aliyuncs.com/icon/tag/renqilong1.png']
            # print(str(i).split("/")[0],len(str(i).split("/")[0])) #['http: 7
            if len(str(i).split("/")[0]) == 7:
                # print(str(i).split("/")[5].split(".")[0]) #renqilong4
                a_list.append(str(i).split("/")[5].split(".")[0])
            else:
                # print("")
                a_list.append("")
        # a_list
        result_["renqi_next_tags"] = a_list
        try:#补丁1->
            result_["hangye_icons"] = result_.icons.str.split("/").apply(pd.Series)[5].str.split(".").apply(pd.Series)[0]
        except:
            result_["hangye_icons"] =""
        #result_["hangye_icons"] = result_.icons.str.split("/").apply(pd.Series)[5].str.split(".").apply(pd.Series)[0]

        #补丁修改地方1-> print(result_[["param","is_new","renqi_next_tags","hangye_icons"]])
        result_ = pd.concat(
            [result_[["param", "is_new", "renqi_next_tags", "hangye_icons"]], df[1].apply(pd.Series).text,
             df[2].apply(pd.Series).text, df[3].apply(pd.Series).text, df[4].apply(pd.Series).text], axis=1)
        # print(df[1].apply(pd.Series).text,df[2].apply(pd.Series).text,df[3].apply(pd.Series).text,df[4].apply(pd.Series).text)

        result_.columns = ["param", "is_new", "renqi_next_tags", "hangye_icons", "涨幅", "30主动", "主净买", "主资金"]
        result_["hangye_icons"] = result_.hangye_icons.str.replace('bk_tag_high', '').str.replace('bk_tag_mid',
                                                                                                  '').str.replace(
            'bk_tag_low', '')
        # print(result_)
    return result_
if __name__ == '__main__':
    a=gn_bk('GN300162',"20210930",2)
    print(a)

